package com.mavenq.fly.utils;

import javax.net.ssl.*;
import java.security.cert.X509Certificate;

public class SSLHelper {

    /**
     * 动态控制是否跳过 SSL 验证（仅用于测试环境）
     * @param skipSSLVerification 如果为 true，则跳过 SSL 验证；false 则启用严格验证
     */
    public static void configureSSL(boolean skipSSLVerification) {
        if (!skipSSLVerification) {
            // 恢复默认的 SSL 验证（严格模式）
            HttpsURLConnection.setDefaultHostnameVerifier(HttpsURLConnection.getDefaultHostnameVerifier());
            HttpsURLConnection.setDefaultSSLSocketFactory(HttpsURLConnection.getDefaultSSLSocketFactory());
            return;
        }

        try {
            // 1. 创建信任所有证书的 TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
            };

            // 2. 初始化 SSLContext，使用信任所有证书的 TrustManager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());

            // 3. 设置全局的 SSLSocketFactory 和 HostnameVerifier
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier((hostname, session) -> true); // 信任所有主机名

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}